package cn.bjxy.shishaolong.system.controller;

import cn.bjxy.shishaolong.common.ResultMsg;
import cn.bjxy.shishaolong.common.StatusCode;
import cn.bjxy.shishaolong.common.SysConst;
import cn.bjxy.shishaolong.system.exception.OperatorFailureException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;

/**
 * 控制器基类
 *
 * @Author 时少龙
 * @Date 2019-04-16 21:45
 * @Version 1.0
 */
public abstract class AbstractController {
    private static Logger logger = LoggerFactory.getLogger(AbstractController.class);

    /**
     * 计算当前页数
     *
     * @param start  偏移量
     * @param length 页大小
     * @return pageNo 当前页数
     */
    public static Integer getPageNo(Integer start, Integer length) {
        Integer pageNo = 1;
        if (++start > 1) {
            pageNo = start / length;
            if (start % length > 0)
                pageNo++;
        }
        return pageNo;
    }

    /**
     * 获取当前用户
     *
     * @param request
     * @return
     */
    public static Integer getCurrentUserId(HttpServletRequest request) {
        Integer userId = (Integer) request.getAttribute(SysConst.CURRENT_USER_ID);
        if (userId == null) {
            throw new OperatorFailureException(StatusCode.SERVER_INNER_ERROR, StatusCode.SERVER_INNER_ERROR_MSG);
        }
        return userId;
    }

    /*==============================返回值相关=======================================*/

    /**
     * 返回参数错误响应
     *
     * @return
     */
    public ResultMsg retParamFailure() {
        return ResultMsg.create(StatusCode.PARAMETER_ERROR, StatusCode.PARAMETER_ERROR_MSG);
    }

    /**
     * 异常时返回的响应实体
     *
     * @param ofe
     * @return
     */
    public ResultMsg retOperatorFalueException(OperatorFailureException ofe) {
        return ResultMsg.create(ofe.getCode(), ofe.getMessage());
    }

    /**
     * 返回成功时的响应实体
     *
     * @return
     */
    public ResultMsg retSuccess() {
        return ResultMsg.success();
    }

    /**
     * 返回删除失败的响应实体
     *
     * @return
     */
    public ResultMsg retDeleteFailure() {
        return ResultMsg.create(StatusCode.DELETE_FAILUER, StatusCode.DELETE_FAILUER_MSG);
    }

    /**
     * 返回操作失败的响应实体
     *
     * @return
     */
    public ResultMsg retOperatorFailure() {
        return ResultMsg.create(StatusCode.OPERATOR_FAILURE, StatusCode.OPERATOR_FAILURE_MSG);
    }

    /**
     * 返回非本人操作的响应实体
     *
     * @return
     */
    public ResultMsg retNotOwnOperatorFailure() {
        return ResultMsg.create(StatusCode.NOT_OWN_OPERATION, StatusCode.NOT_OWN_OPERATION_MSG);
    }

    /**
     * 返回查询失败时的响应实体
     *
     * @return
     */
    public ResultMsg retQueryFailure() {
        return ResultMsg.create(StatusCode.QUERY_FAILURE, StatusCode.QUERY_FAILURE_MSG);
    }

    /**
     * 返回保存失败时的响应实体
     *
     * @return
     */
    public ResultMsg retSaveFailure() {
        return ResultMsg.create(StatusCode.SAVE_FAILURE, StatusCode.SAVE_FAILURE_MSG);
    }
}
